package cn.project.engineering.utils;

import android.app.Application;
import android.content.Intent;

import androidx.annotation.NonNull;
import cn.project.engineering.GwApplication;
import cn.project.engineering.ui.SplashActivity;
import log.KLog;

public  class MyCrashHandler implements Thread.UncaughtExceptionHandler {

    public  static  String TAG="MyCrashHandle";
    public  GwApplication mgwApplication;

    private Thread.UncaughtExceptionHandler mOldHandler;

    @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
        KLog.d(TAG,"程序出现错误了 Thread=="+thread.getName()+"Throwable="+throwable.getMessage());
        Intent intent=new Intent(mgwApplication, SplashActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mgwApplication.startActivity(intent);
        if (mOldHandler != null && !mOldHandler.getClass().getName().startsWith("com.android.internal.os")) {
            mOldHandler.uncaughtException(thread, throwable);
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }

    public MyCrashHandler(GwApplication mgwApplication) {
        mOldHandler = Thread.getDefaultUncaughtExceptionHandler();
        this.mgwApplication = mgwApplication;
        if (getClass().getName().equals(mOldHandler.getClass().getName())) {
            // 请不要重复注册 Crash 监听
            throw new IllegalStateException("are you ok?");
        }
    }
    /**
     * 注册 Crash 监听
     */
    public static void register(GwApplication application) {
        Thread.setDefaultUncaughtExceptionHandler(new MyCrashHandler(application));
    }
}
